import { observe } from ".";

let oldArrayPrototype = Array.prototype;

export let arrayMethods = Object.create(Array.prototype);
// arrayMethods.__proto__ = Array.prototype继承

let methods = ["push", "shift", "unshift", "pop", "reverse", "sort", "splice"];

methods.forEach((method) => {
  // 以上七个方法用重写后的方法
  arrayMethods[method] = function (...args) {
    console.log("数组发生变化");
    oldArrayPrototype[method].call(this, ...args);
    let inserted;
    let ob = this.__ob__
    switch (method) {
      case "push":
      case "unshift":
        inserted = args;
        break;
      case "splice":
        inserted = args.slice(2);
        break;
    }
    // 如果有新增内容 进行继续劫持 需要观测数组的每一项 而不是数组
    if (inserted) {
        ob.observeArray(inserted)
    }
    // 数组observer.dep属性
    ob.dep.notify()
  };
});
